<template>
  <div id="auction-time-admin">
    <a-card title="拍卖时间管理" :bordered="false">
      <a-form class="form">
        <a-row class="form-row">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="选择开始拍卖时间">
              <a-date-picker
                v-model="startValue"
                :disabled-date="disabledStartDate"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="开始时间"
                @openChange="handleStartOpenChange"
              />
            </a-form-item>
          </a-col>
          <a-col
            :xl="{ span: 6, offset: 2 }"
            :lg="{ span: 8, offset: 2 }"
            :md="{ span: 12 }"
            :sm="24"
          >
            <a-form-item label="选择结束拍卖时间">
              <a-date-picker
                v-model="endValue"
                :disabled-date="disabledEndDate"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                :open="endOpen"
                @openChange="handleEndOpenChange"
              />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <div class="btn">
              <a-button @click="addAuction" type="primary">添加</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <div style="margin-bottom: 16px">
        <a-button
          type="primary"
          :disabled="!hasSelected"
          @click="deleteAuction"
        >
          删除
        </a-button>
        <span style="margin-left: 8px">
          <template v-if="hasSelected">
            选中{{ selectedRowKeys.length }}个，确认删除
          </template>
        </span>
      </div>
      <advance-table
        :columns="columns"
        :data-source="auctions.data"
        title="拍卖时间段"
        :loading="false"
        rowKey="id"
        :format-conditions="true"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :pagination="{
          current: page,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: onPageChange,
          onShowSizeChange: onSizeChange,
        }"
      >
        <template slot="time" slot-scope="{ text }">
          {{ text | filterDate("yyyy-MM-dd hh:mm:ss") }}
        </template>
        <template slot="action" slot-scope="{ text }">
          <a href="#" @click="updateAuction(text);isShowEditPop=true"> 修改 </a>
        </template>
      </advance-table>
    </a-card>
    <EditAuctionTimePop
      :updateData="{...updateData}"
      :show="isShowEditPop"
      @close="isShowEditPop = false"
    />
  </div>
</template>

<script>
import AdvanceTable from "@/components/table/advance/AdvanceTable";
import { addAuction, delAuction } from "@/api";
import formatDate from "@/utils/formatDate";
import { mapState } from "vuex";
import EditAuctionTimePop from "./EditAuctionTimePop";
export default {
  name: "AuctionTimeAdmin",
  components: {
    AdvanceTable,
    EditAuctionTimePop,
  },
  data() {
    return {
      columns: [
        {
          title: "id",
          dataIndex: "id",
        },
        {
          title: "标题",
          dataIndex: "title",
        },
        {
          title: "开始时间",
          dataIndex: "starttime",
          scopedSlots: { customRender: "time" },
        },
        {
          title: "结束时间",
          dataIndex: "endtime",
          scopedSlots: { customRender: "time" },
        },
        {
          title: "状态",
          dataIndex: "status",
        },
        {
          title: "操作",
          scopedSlots: { customRender: "action" },
        },
      ],

      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
      conditions: {},

      // 时间
      startValue: null,
      endValue: null,
      endOpen: false,

      // 多选
      selectedRowKeys: [],

      // 修改时间的数据
      updateData: {},

      // 是否弹出修改框
      isShowEditPop: false,
    };
  },
  filters: {
    filterDate(value, fmt) {
      let getDate = new Date(value);
      let o = {
        "M+": getDate.getMonth() + 1,
        "d+": getDate.getDate(),
        "h+": getDate.getHours(),
        "m+": getDate.getMinutes(),
        "s+": getDate.getSeconds(),
        "q+": Math.floor((getDate.getMonth() + 3) / 3),
        S: getDate.getMilliseconds(),
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (getDate.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
  },
  methods: {
    onSearch(conditions, searchOptions) {
      console.log(searchOptions);
      this.page = 1;
      this.$store.dispatch("auctions", {
        pageIndex: this.page,
        pageSize: this.pageSize,
      });
    },
    onSizeChange(current, size) {
      this.page = 1;
      this.pageSize = size;
      this.$store.dispatch("auctions", {
        pageIndex: this.page,
        pageSize: this.pageSize,
      });
    },
    onRefresh(conditions) {
      this.conditions = conditions;
      this.$store.dispatch("auctions", {
        pageIndex: this.page,
        pageSize: this.pageSize,
      });
    },
    onReset(conditions) {
      this.conditions = conditions;
      this.$store.dispatch("auctions", {
        pageIndex: this.page,
        pageSize: this.pageSize,
      });
    },
    onPageChange(page, pageSize) {
      this.page = page;
      this.pageSize = pageSize;
      this.$store.dispatch("auctions", {
        pageIndex: this.page,
        pageSize: this.pageSize,
      });
    },

    disabledStartDate(startValue) {
      const endValue = this.endValue;
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.startValue;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },

    // 添加拍卖会
    async addAuction() {
      let { startValue, endValue } = this;
      if (startValue == null || endValue == null) {
        this.$message.error("请输入日期！");
        return;
      }
      let start = formatDate(new Date(startValue), "YYYY-mm-dd HH:MM:SS");
      let end = formatDate(new Date(endValue), "YYYY-mm-dd HH:MM:SS");
      // 发起请求
      let result = await addAuction(start, end);
      if (result.flag) {
        this.$message.success(result.msg);
        // 重新获取数据
        this.$store.dispatch("auctions", {
          pageIndex: this.page,
          pageSize: this.pageSize,
        });
        // 清空日期
        this.startValue = null;
        this.endValue = null;
      } else {
        this.$message.error(result.msg);
      }
    },

    // 删除拍卖会
    async deleteAuction() {
      let ids = this.selectedRowKeys.toString();
      let result = await delAuction(ids);
      if (result.flag) {
        this.$message.success(result.msg);
        // 重新加载数据
        this.$store.dispatch("auctions", {
          pageIndex: this.page,
          pageSize: this.pageSize,
        });
      } else {
        this.$message.error(result.msg);
      }
    },

    // 修改拍卖会
    updateAuction(data) {
      this.updateData = data;
    },

    // 多选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
  },

  mounted() {
    this.$store.dispatch("auctions", {
      pageIndex: this.page,
      pageSize: this.pageSize,
    });
  },

  watch: {
    auctions(newValue) {
      this.total = newValue.count;
    },
  },

  computed: {
    ...mapState({
      auctions: (store) => store.auction.auctions,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
};
</script>
<style lang="less" scoped>
.form {
  .form-row {
    margin: 0 -8px;
  }
  .ant-col-md-12,
  .ant-col-sm-24,
  .ant-col-lg-6,
  .ant-col-lg-8,
  .ant-col-lg-10,
  .ant-col-xl-8,
  .ant-col-xl-6 {
    padding: 0 8px;
  }
  .btn {
    margin-left: 8px;
  }
}
</style>
